/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package com.ez2find.manager;

import com.ez2find.model.Area;
import com.ez2find.model.Community;
import com.ez2find.model.CommunityCategorie;
import com.ez2find.model.RegisterUser;
import com.ez2find.model.Site;
import java.util.List;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;

/**
 *
 * @author Owner
 */
@Stateless
public class CommunityManagerBean implements CommunityManagerLocal {
    
    @PersistenceContext
    private EntityManager em;
    
    public void create(Community community)throws Exception {
        em.persist(community);
    }
 
    public void update(Community community)throws Exception {
        em.merge(community);
    }
    
    public Community merge(Community community)throws Exception {
        return em.merge(community);
    }
    
    public void delete(Community community)throws Exception {
        community=em.merge(community);
        em.remove(community);
    }
    
    public Community find(long id){
        return em.find(Community.class,id);
    }

    public List<Community> listAll(){
        Query query=em.createNamedQuery("listAllCommunitis");
        List<Community> result=query.getResultList();
        return result;
    }
    
    public long lastCode(){
        try{
            Query query=em.createNamedQuery("lastCommunityCode");
            return (Long) query.getSingleResult();
        }catch(Exception ex){
            return 0;
        }
    }
    
    public List<Community> listCommunitisSite(Site site, boolean communityC, CommunityCategorie communityCategorie, String consult){
        Query query=em.createQuery("SELECT c FROM Community c WHERE c.site=:site AND c.status='active'"+consult+" ORDER BY c.publishDate DESC, c.code DESC");
        query.setParameter("site", site);
        if(communityC)
            query.setParameter("communityCategorie", communityCategorie);
        List<Community> result=query.getResultList();
        return result;
    }
    
    public List<Community> listCommunitisArea(Area area, boolean communityC, CommunityCategorie communityCategorie, String consult){
        Query query=em.createQuery("SELECT c FROM Community c WHERE c.area=:area AND c.status='active'"+consult+" ORDER BY c.publishDate DESC, c.code DESC");
        query.setParameter("area", area);
        if(communityC)
            query.setParameter("communityCategorie", communityCategorie);
        List<Community> result=query.getResultList();
        return result;
    }
    
}
